﻿using System.Security.Cryptography;
using System.Text;

namespace TMV.Report
{
	public class MyDES
	{

		//密钥向量 
		private static byte[] Keys = Encoding.GetEncoding("GBK").GetBytes("ZR199806");
		/// <summary> 
		/// DES加密字符串 
		/// </summary> 
		/// <param name="encryptString">待加密的字符串</param> 
		/// <param name="encryptKey">加密密钥,要求为16位</param> 
		/// <returns>加密成功返回加密后的字符串，失败返回源串</returns> 
		public static Byte[] DESEncrypt(string encryptString, string encryptKey = "BJZHIREN")
		{
			try
			{
				byte[] rgbKey = Encoding.GetEncoding("GBK").GetBytes(encryptKey);
				byte[] rgbIV = Keys;
				byte[] inputByteArray = Encoding.GetEncoding("GBK").GetBytes(encryptString);
				var DCSP = DES.Create();
				//DCSP.Mode = CipherMode.ECB;
				MemoryStream mStream = new MemoryStream();
				CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
				cStream.Write(inputByteArray, 0, inputByteArray.Length);
				cStream.FlushFinalBlock();
				return mStream.ToArray();
			}
			catch (Exception ex)
			{
				return Encoding.GetEncoding("GBK").GetBytes(encryptString);
			}

		}
		/// <summary> 
		/// DES解密字符串 
		/// </summary> 
		/// <param name="decryptString">待解密的字符串</param> 
		/// <param name="decryptKey">解密密钥,要求为16位,和加密密钥相同</param> 
		/// <returns>解密成功返回解密后的字符串，失败返源串</returns> 
		public static string DESDecrypt(string decryptString, string decryptKey = "BJZHIREN")
		{
			try
			{
				byte[] rgbKey = Encoding.GetEncoding("GBK").GetBytes(decryptKey);
				byte[] rgbIV = Keys;
				byte[] inputByteArray = Convert.FromBase64String(decryptString);
				var DCSP = Aes.Create();
				MemoryStream mStream = new MemoryStream();
				CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
				Byte[] inputByteArrays = new byte[inputByteArray.Length];
				cStream.Write(inputByteArray, 0, inputByteArray.Length);
				cStream.FlushFinalBlock();
				return Encoding.GetEncoding("GBK").GetString(mStream.ToArray());
			}
			catch (Exception ex)
			{
				return ex.Message + decryptString;
			}

		}
	}
}